package com.sky.interceptor;

import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.AccountNotFoundException;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
public class AdminTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求的URL
        StringBuffer url = request.getRequestURL();
        log.info("拦截的url:{}",url);

        //2.判断是否是动态资源，如果不是动态资源直接放行
        if(handler instanceof HandlerMethod){
            return true;
        }

        //3.获取token
        String token = request.getHeader("token");
        if(token == null){
            throw new AccountNotFoundException(MessageConstant.USER_NOT_LOGIN);
        }

        //4.解析token
        try {
            //4.1 解析token成功，则表示已经登录过
            Claims claims = JwtUtil.parseJWT("mjxy", token);
            //获取登录的用户id
            Long empId = Long.valueOf(claims.get("empId").toString());
            log.info("当前已登录用户id:{}",empId);
            BaseContext.setCurrentId(empId);
            return true; //放行
        } catch (Exception e) {
            //4.1 解析token失败，则表示token失效、获取没有token
            log.info("token解析失败");
            throw new AccountNotFoundException(MessageConstant.USER_NOT_LOGIN);
        }
    }
}